package com.imonsoft.common.util;

import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;


import javax.activation.*;

import com.imonsoft.common.exception.SystemException;

import java.io.*;

public class SendMail {

	private MimeMessage mimeMsg; // MIME邮件对象
	private Session session; // 邮件会话对象
	private Properties props; // 系统属性
	@SuppressWarnings("unused")
	private boolean needAuth = false; // smtp是否需要认证
	private String username = ""; // smtp认证用户名和密码
	private String password = "";
	private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

	/**
	 * 构造函数一
	 */
	public SendMail() {
		// setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取
		createMimeMessage();
	}

	/**
	 * 构造函数二
	 */
	public SendMail(String smtp) {
		setSmtpHost(smtp);
		createMimeMessage();
	}

	/**
	 * 构造函数三
	 */
	public SendMail(String smtp, String userName, String userPwd) {
		setSmtpHost(smtp);
		createMimeMessage(userName, userPwd);
	}

	/**
	 * 设置邮箱服务器地址
	 * 
	 * @param hostName
	 */
	public void setSmtpHost(String hostName) {
		System.out.println("设置系统属性：mail.smtp.host = " + hostName);
		if (props == null)
			props = System.getProperties(); // 获得系统属性对象
		props.put("mail.smtp.host", hostName); // 设置SMTP主机
	}

	/**
	 * @desc 创建邮件会话对象
	 * @param userName
	 *            用户名
	 * @param userPwd
	 *            密码
	 * @return boolean
	 */

	public boolean createMimeMessage(String userName, String userPwd)

	{
		try {
			setNamePass(userName, userPwd);
			System.out.println("准备获取邮件会话对象！");
			// 创建邮件会话
			session = Session.getDefaultInstance(props, new Authenticator() { // 验账账户
						@Override
						public PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username,
									password);
						}
					});
			// session = Session.getDefaultInstance(props,null); //获得邮件会话对象
		} catch (Exception e) {
			System.err.println("获取邮件会话对象时发生错误！" + e);
			return false;
		}
		System.out.println("准备创建MIME邮件对象！");
		try {
			mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
			mp = new MimeMultipart();
			return true;
		} catch (Exception e) {
			System.err.println("创建MIME邮件对象失败！" + e);
			return false;
		}
	}

	public boolean createMimeMessage() {

		try {
			System.out.println("准备获取邮件会话对象！");
			// 创建邮件会话
			session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
		} catch (Exception e) {
			System.err.println("获取邮件会话对象时发生错误！" + e);
			return false;
		}
		System.out.println("准备创建MIME邮件对象！");
		try {
			mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
			mp = new MimeMultipart();
			return true;
		} catch (Exception e) {
			System.err.println("创建MIME邮件对象失败！" + e);
			return false;
		}
	}

	/**
	 * 邮箱服务器认证
	 * 
	 * @param need
	 */

	public void setNeedAuth(boolean need) {

		System.out.println("设置smtp身份认证：mail.smtp.auth = " + need);
		if (props == null)
			props = System.getProperties();
		if (need) {
			props.put("mail.smtp.auth", "true");
		} else {
			props.put("mail.smtp.auth", "false");
		}
	}

	/**
	 * 初始化发信人的用户名和密码
	 * 
	 * @param name
	 * @param pass
	 */
	public void setNamePass(String name, String pass) {

		username = name;
		password = pass;

	}

	/**
	 * 设置邮件主题（标题）
	 * 
	 * @param mailSubject
	 * @return
	 */

	public boolean setSubject(String mailSubject) {
		System.out.println("设置邮件主题！");
		try {
			mimeMsg.setSubject(mailSubject);
			return true;
		} catch (Exception e) {
			System.err.println("设置邮件主题发生错误！");
			return false;
		}
	}

	/**
	 * 设置邮件正文
	 * 
	 * @param mailBody
	 * @return
	 */

	public boolean setBody(String mailBody) {

		try {
			BodyPart bp = new MimeBodyPart();
			bp.setContent("" + mailBody, "text/html;charset=GB2312");
			mp.addBodyPart(bp);
			return true;
		} catch (Exception e) {
			System.err.println("设置邮件正文时发生错误！" + e);
			return false;
		}
	}

	/**
	 * 添加单个附件
	 * 
	 * @param filename
	 * @return
	 */
	public boolean addFileAffix(String filename) {

		System.out.println("增加邮件附件：" + filename);

		try {

			// 附件的处理
			MimeBodyPart mbp2 = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(filename);
			mbp2.setDataHandler(new DataHandler(fds));
			mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "GB2312",
					"B"));
			mp.addBodyPart(mbp2);

			return true;

		}

		catch (Exception e) {

			System.err.println("增加邮件附件：" + filename + "发生错误！" + e);

			return false;

		}

	}

	/**
	 * 添加多个附件方法一
	 * 
	 * @param filenames
	 * @return
	 */

	public boolean addFileAffix(String[] filenames) {

		try {
			File file;
			MimeBodyPart mbp2 = null;
			FileDataSource fds = null;

			// 附件的处理
			for (int i = 0; i < filenames.length; i++) {
				file = new File(filenames[i]);
				if (file.exists()) {
					System.out.println("增加邮件附件：" + filenames[i]);
					mbp2 = new MimeBodyPart();
					fds = new FileDataSource(filenames[i]);
					mbp2.setDataHandler(new DataHandler(fds));
					mbp2.setFileName(MimeUtility.encodeText(fds.getName(),
							"GB2312", "B"));

					mp.addBodyPart(mbp2);
				}
			}
			return true;
		} catch (Exception e) {
			System.err.println("增加邮件附件发生错误！" + e);
			return false;
		}
	}

	/**
	 * 添加多个附件方法二
	 * 
	 * @param filenames
	 * @return
	 */

	@SuppressWarnings("rawtypes")
	public boolean addFileAffix(List fileList) {

		try {
			File file;
			MimeBodyPart mbp2 = null;
			FileDataSource fds = null;
			// 附件的处理
			for (int i = 0; i < fileList.size(); i++) {
				file = new File((String) fileList.get(i));
				if (file.exists()) {
					System.out.println("增加邮件附件：" + fileList.get(i).toString());
					mbp2 = new MimeBodyPart();
					fds = new FileDataSource((String) fileList.get(i));
					mbp2.setDataHandler(new DataHandler(fds));
					mbp2.setFileName(MimeUtility.encodeText(fds.getName(),
							"GB2312", "B"));
					mp.addBodyPart(mbp2);
				}
			}
			return true;
		} catch (Exception e) {
			System.err.println("增加邮件附件发生错误！" + e);
			return false;
		}
	}

	/**
	 * 设置发信人
	 * 
	 * @param from
	 * @return
	 */

	public boolean setFrom(String from) {

		System.out.println("设置发信人！");

		try {

			mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人

			return true;

		}

		catch (Exception e)

		{
			return false;
		}

	}

	/**
	 * 设置收信人
	 * 
	 * @param to
	 * @return
	 */
	public boolean setTo(String to) {

		if (to == null)
			return false;
		try {
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
					.parse(to));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 
	 * @param name
	 *            String
	 * 
	 * @param pass
	 *            String
	 */

	public boolean setCopyTo(String copyto)

	{

		if (copyto == null)
			return false;

		try {

			mimeMsg.setRecipients(Message.RecipientType.CC,
					(Address[]) InternetAddress.parse(copyto));

			return true;

		}

		catch (Exception e)

		{
			return false;
		}

	}

	/**
	 * 邮件发送
	 * 
	 * @return
	 */

	public boolean sendout()

	{
		String errorMsg="";
		try {
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			System.out.println("正在发送邮件....");
			Transport.send(mimeMsg);
			System.out.println("发送邮件成功！");
			return true;
		} catch (Exception e) {
			errorMsg="邮件发送失败！";
			System.err.println("邮件发送失败！" + e);
			return false;
		}finally{
			if(StringUtil.isNotEmpty(errorMsg)){
				throw new SystemException("邮件发送失败");
			}
		}
	}

	/**
	 * 发送测试
	 */

	public static void main(String[] args) {
//
//		String mailbody = "邮件发送测试！！！";
//		SendMail themail = new SendMail("smtp.qq.com","64925141@qq.com","wangxin" );
//		themail.setNeedAuth(true);
//		if (themail.setSubject("JavaMail测试") == false)
//			return;
//		if (themail.setBody(mailbody) == false)
//			return;
//		if (themail.setTo("64925141@qq.com") == false)
//			return;
//		if (themail.setFrom("64925141@qq.com") == false)
//			return;
//		// 添加附件
//		if (themail.addFileAffix("D://QQ截图20130606110247.png") == false)
//			return;
//
//		if (themail.sendout() == false)
//			return;
		sendMail("邮件发送测试！！！","smtp.qq.com","64925141@qq.com","wangxin","JavaMail测试","582207245@qq.com","D://specialClaim.xls");
	}
	public static void sendMail(String mailbody,String mailserver,String from,String pwd,String tittle,String to,String filePath){
//		mailbody = "邮件发送测试！！！";
//		mailserver="smtp.qq.com";
//		from="64925141@qq.com";
//	    pwd="wangxin";
//	    tittle="JavaMail测试";
//	    to="64925141@qq.com";
		SendMail themail = new SendMail(mailserver,from,pwd);
		themail.setNeedAuth(true);
		if (themail.setSubject(tittle) == false)
			return;
		if (themail.setBody(mailbody) == false)
			return;
		if (themail.setTo(to) == false)
			return;
		if (themail.setFrom(from) == false)
			return;
		// 添加附件
		if (themail.addFileAffix(filePath) == false)
			return;

		if (themail.sendout() == false)
			return;
	}
}
